package demo.java.parallelprogram.threadpool;

import java.util.List;
import java.util.Vector;

public class ThreadPlool {

	private static ThreadPlool instance = null;
	
	private List<PThread> idleThreads;//空闲的线程队列
	private int threadCounter;
	private boolean isShutDown = false;
	
	public ThreadPlool() {
		this.idleThreads = new Vector(5);
		threadCounter = 0;
	}
	
	public int getCreatedThreadsCount(){
		return threadCounter;
	}
	
	//取得线程池的实例
	public synchronized static ThreadPlool getInstance(){
		if(instance == null){
			instance = new ThreadPlool();
		}
		return  instance;
	}
	
	//将线程放入线程池
	protected synchronized void repool(PThread repoolingThread){
		if(!isShutDown){
			idleThreads.add(repoolingThread);
		}else{
			repoolingThread.setShutDown();
		}
	}
	
	//停止所有的线程
	public synchronized void shutdown(){
		isShutDown = true;
		for(int i=0;i< idleThreads.size();i++){
			PThread idleThread  = (PThread) idleThreads.get(i);
			idleThread.setShutDown();
		}
	}
	
	
	public synchronized void start(Runnable target){
		PThread thread = null;
		System.out.println("空闲 的线程队列idleThreads:"+idleThreads.size());
//		System.out.println("threadCounter:"+threadCounter);
		if(idleThreads.size() > 0){
			int lastIndex=idleThreads.size()-1;
			thread = (PThread)  idleThreads.get(lastIndex);
			idleThreads.remove(lastIndex);
			thread.setTarget(target);
		}else{
			threadCounter++;
			thread = new PThread(target, "PThread #"+threadCounter, this);
			thread.start();
		}
	}
	
	
	
	
	
	
	
	
	
	
}
